﻿ 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.Sqlite
{
    /// <summary>
    /// 备份服务使用示例
    /// </summary>
    public class BackupServiceDemo
    {
        private readonly SqliteBackupService _backupService;
        private System.Timers.Timer _backupTimer;

        public BackupServiceDemo(string databasePath)
        {
            // 创建备份目录（相对于数据库文件）
            string backupDirectory = Path.Combine(
                Path.GetDirectoryName(databasePath),
                "backups"
            );

            // 初始化备份服务
            _backupService = new SqliteBackupService(databasePath, backupDirectory);

            // 设置定时备份（例如每6小时执行一次）
            SetupScheduledBackups(TimeSpan.FromHours(6));
        }

        /// <summary>
        /// 设置定时备份
        /// </summary>
        /// <param name="interval">备份时间间隔</param>
        public void SetupScheduledBackups(TimeSpan interval)
        {
            _backupTimer = new System.Timers.Timer(interval.TotalMilliseconds);
            _backupTimer.Elapsed += async (sender, e) =>
            {
                await _backupService.ScheduledBackupAsync();
            };
            _backupTimer.Start();

            Console.WriteLine($"已设置定时备份，间隔: {interval}");
        }

        /// <summary>
        /// 手动触发备份
        /// </summary>
        /// <returns>备份文件路径</returns>
        public string TriggerManualBackup()
        {
            Console.WriteLine("开始手动备份...");
            return _backupService.ManualBackup();
        }

        /// <summary>
        /// 展示所有可用备份
        /// </summary>
        public void ShowAvailableBackups()
        {
            var backups = _backupService.GetBackupList();

            Console.WriteLine("可用备份列表:");
            Console.WriteLine("----------------------------------------");
            foreach (var backup in backups)
            {
                string status = backup.IsValid ? "有效" : "无效";
                double sizeInMB = Math.Round(backup.Size / 1024.0 / 1024.0, 2);

                Console.WriteLine($"文件名: {backup.FileName}");
                Console.WriteLine($"创建时间: {backup.CreationTime}");
                Console.WriteLine($"大小: {sizeInMB} MB");
                Console.WriteLine($"状态: {status}");
                Console.WriteLine("----------------------------------------");
            }
        }

        /// <summary>
        /// 从指定备份恢复
        /// </summary>
        /// <param name="backupFileName">备份文件名</param>
        public void RestoreFromBackup(string backupFileName)
        {
            var backups = _backupService.GetBackupList();
            var selectedBackup = backups.FirstOrDefault(b => b.FileName == backupFileName);

            if (selectedBackup == null)
            {
                Console.WriteLine($"错误: 未找到备份文件 '{backupFileName}'");
                return;
            }

            if (!selectedBackup.IsValid)
            {
                Console.WriteLine($"警告: 备份文件 '{backupFileName}' 可能已损坏，是否继续恢复? (y/n)");
                string response = Console.ReadLine().ToLower();
                if (response != "y")
                {
                    Console.WriteLine("恢复操作已取消");
                    return;
                }
            }

            Console.WriteLine($"开始从备份 '{backupFileName}' 恢复数据库...");
            _backupService.RestoreDatabase(selectedBackup.FilePath);
            Console.WriteLine("数据库恢复完成!");
        }

        /// <summary>
        /// 停止备份服务
        /// </summary>
        public void Shutdown()
        {
            _backupTimer?.Stop();
            _backupTimer?.Dispose();
            Console.WriteLine("备份服务已关闭");
        }
    }
}
